<?php
namespace App\Http\Controllers\User\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;

class SettingController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth:user');
    }

    public function showSettingForm(Request $request)
    {
        return view('user.auth.setting', ['user' => $request->user('user')]);
    }

    public function setting(Request $request)
    {
        $this->validateSetting($request);
        $user = $request->user('user');
        $data = $request->only(['password']);
        if (!empty($data['password'])) {
            $user->password = Hash::make($data['password']);
        }
        $user->save();
        return redirect()->back()->with('success', '修改成功');
    }

    public function validateSetting(Request $request)
    {
        $request->validate([
            'password' => ['string', 'regex:/^[a-zA-Z0-9_.!@#$%^&*-+]{4,32}$/']
        ], [
            'password.string'    => '密码格式错误',
            'password.regex'     => '由4-32位英文字母、数字或符号组成',
        ]);
    }

    protected function guard()
    {
        return Auth::guard('user');
    }
}
